<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/07
 * Time: 13:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;


use app\admin\controller\BaseController;
use app\common\model\ProductUnit;
use app\common\service\product\ProductService;
use think\facade\Validate;

class UnitController extends BaseController
{
    public function index()
    {
        if($this->request->isAjax())
        {
            $unit = ProductUnit::order("sort desc, unit_id desc")->select();
            $this->assign("list", $unit);
            return $this->fetch("lists");
        }
        return $this->fetch("index");
    }

    /**
     * 添加计量单位
     * @date 2020/09/14
     * @author longli
     */
    public function add()
    {
        $unitId = $this->request->request("unit_id");
        if(!empty($unitId)) $this->assign("unit", ProductUnit::get($unitId));
        return $this->fetch("add");
    }

    /**
     * 更新计量单位信息
     * @date 2020/09/14
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'name_ch'  => 'require',
            ],[
                'name_ch.require' => '中文名必填',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ProductUnit::IS_NO;
        }
        else
        {
            $validate = Validate::make([
                'unit_id'  => 'require',
            ],[
                'unit_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['unit_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        ProductService::getInstance()->addUnit($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 删除计量单位
     * @date 2020/09/14
     * @author longli
     */
    public function delete()
    {
        $unitId = $this->request->request("ids");
        if(empty($unitId)) $this->error('参数错误');
        ProductUnit::destroy($unitId);
        $this->success('删除成功');
    }
}